<template>
<basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page="page" :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @on-load="onLoad" @cell-click="handleCellClick">
        <template slot-scope="{size}" slot="menuLeft">
            <el-button type="danger" :size="size" icon="el-icon-delete" plain v-if="permission.fileinfo_delete" @click="handleDelete">删除
            </el-button>
            <el-button type="success" :size="size" plain v-if="userInfo.authority.includes('admin')" icon="el-icon-upload2" @click="handleImport">直传minio
            </el-button>
        </template>

        <template slot-scope="{type,disabled}" slot="createDateForm">

            <avue-form :option="option2" v-model="form2" :upload-before="uploadBefore" :upload-after="uploadAfter" :disabled="disabled">

            </avue-form>
        </template>
    </avue-crud>
    <vxe-modal title="预签名URL文件上传" v-model="excelBox" width="555" @confirm="onUploadConfirm" transfer showFooter>
        <el-upload ref="upload" class="upload-img-preview" list-type="picture-card" accept="image/*" action="" :http-request="httpRequest" :multiple="true" :auto-upload="false" :limit="uploadNumberLimit()" :before-upload="beforeUpload" :on-success="onUploadSuccess" :on-error="onUploadError" :on-exceed="onUploadExceedTip">
            <i class="el-icon-plus"></i>
        </el-upload>
    </vxe-modal>

    <vxe-modal title="预览图" v-model="cellImage" width="555" transfer >
        <el-image :src="clickCellImage"></el-image>
    </vxe-modal>
</basic-container>
</template>

<script>
import {
    getList,
    getDetail,
    add,
    update,
    deleteFile,
    remove,
    ossInfo,
    minIoImgUpdate
} from "@/api/base/fileinfo";
import {
    mapGetters
} from "vuex";
import {
    dateFormat
} from "@/util/date";

export default {
    data() {
        return {
            type: null,
            form2: {
                imgUrl: [],
            },
            option2: {
                menuBtn: false,
                column: [

                    {
                        label: '',
                        labelWidth: 1,
                        prop: 'imgUrl',
                        type: 'upload',
                        loadText: '附件上传中，请稍等',
                        span: 24,
                        propsHttp: {
                            res: 'data'
                        },
                        tip: '只能上传jpg/png文件，且不超过500kb',
                        action: '/system/file/upload',
                    }
                ]
            },
            excelBox: false,
            form: {},
            query: {},
            loading: true,
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            selectionList: [],
            option: {
                height: 'auto',
                calcHeight: 180,
                searchShow: true,
                searchMenuSpan: 6,
                tip: false,
                border: true,
                index: true,
                viewBtn: true,
                selection: true,
                column: [{
                        label: "文件md5",
                        prop: "id",
                        display: false,
                    },
                    {
                        label: "文件名称",
                        prop: "name",
                        display: false,
                        rules: [{
                            required: true,
                            message: "请输入文件名称",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "文件类型",
                        prop: "contentType",
                        display: false,
                    },
                    {
                        label: "文件大小",
                        prop: "fileSize",
                        display: false,
                    },
                    {
                        label: "物理路径",
                        prop: "path",
                        display: false,
                    },
                    {
                        label: "url地址",
                        prop: "url",
                        display: false,
                        type: 'url',
                    },
                    {
                        label: "来源",
                        prop: "source",
                        display: false,
                    },
                    {
                        label: "文件",
                        prop: "createDate",
                        hide: true,
                        formslot: true,
                        //dataType: 'string',
                        // type: 'upload',
                        // loadText: '附件上传中，请稍等',
                        // span: 24,
                        // propsHttp: {
                        //     url: 'url',
                        //     name: 'name',
                        //     res: 'data'
                        // },
                        // tip: '只能上传jpg/png文件，且不超过500kb',
                        // action: '/system/file/upload',
                    },
                ]
            },
            data: [],
            options: {
                multiple: true, // 是否支持选取多个图片
                limit: 20, // 最多可选择图片数量
                maxSize: 2, // 最大尺寸（M）
                activeTab: 'pick',
                enableUpload: false, // 是否启用图片上传
                callback: null
            },
            images: [], // 已选图片
            ossList: [],
            cellImage: false
        };
    },
    computed: {
        ...mapGetters(["userInfo", "permission"]),
        permissionList() {
            return {
                addBtn: this.vaildData(this.permission.fileinfo_edit, false),
                viewBtn: this.vaildData(this.permission.fileinfo_view, false),
                delBtn: this.vaildData(this.permission.fileinfo_edit, false),
                editBtn: this.vaildData(this.permission.fileinfo_edit, false)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    methods: {
        rowSave(row, done, loading) {
            add(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowUpdate(row, index, done, loading) {
            update(row).then(() => {
                done();
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            }, error => {
                window.console.log(error);
                loading();
            });
        },
        rowDel(row) {
            this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    return remove(row.id);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                });
        },
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                .then(() => {
                    return remove(this.ids);
                })
                .then(() => {
                    this.onLoad(this.page);
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.$refs.crud.toggleSelection();
                });
        },
        beforeOpen(done, type) {
            this.type = type
            if (["edit", "view"].includes(type)) {
                getDetail(this.form.id).then(res => {
                    this.form = res.data.data;
                    this.form2 = {
                        imgUrl: [{
                            "label": this.form.name,
                            "value": this.form.url
                        }]
                    }
                });
            }
            done();
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        onLoad(page, params = {}) {
            this.loading = true;
            getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            });
        },
        uploadBefore(file, done, loading, column) {
            console.log(file, column)
            //如果你想修改file文件,由于上传的file是只读文件，必须复制新的file才可以修改名字，完后赋值到done函数里,如果不修改的话直接写done()即可
            /* var newFile = new File([file], '1234', {
                type: file.type
            }); */
            done(file)
            this.$message.success('上传前的方法')
        },
        uploadAfter(res, done, loading, column) {
            console.log(res, column)
            done()
            if (this.type == 'edit') {
                //编辑就是新加一个再删除原文件
                deleteFile(this.form.id).then(res => {
                    this.onLoad(this.page);
                    this.type = null
                })
            }
            this.$message.success('上传后的方法')
        },
        handleImport() {
            this.excelBox = true;
        },
        handleCellClick(row, column, cell, event) {
            if (column.property == "name") {
                console.log(row.path)
                let fileNames = row.path
                ossInfo(fileNames,"v").then(response => {
                    this.clickCellImage = response.data.data[0].link
                    this.cellImage = true
                })

            }
        },
        uploadNumberLimit() {
            if (!this.options.multiple) {
                return 1
            }
            return this.options.limit - this.images.length
        },
        /**
         * 获取上传图片数据
         */
        onUploadConfirm() {
            let files = this.$refs.upload.uploadFiles
            if (files.length) {
                let fileNames = files.map(e => e.name).join(',')
                console.log(fileNames)
                ossInfo(fileNames).then(response => {
                    console.log('选择图片response：', response)
                    this.ossList = response.data.data
                    this.notImg = true
                    this.$nextTick(() => {
                        this.$refs.upload.submit()
                    })
                })
            }
        },
        /**
         * 上传图片
         */
        httpRequest(event) {
            console.log('上传图片event:', event)

            let file = event.file
            let typeArray = file.type.split('/')
            const attachFile = Object.assign({
                contentType: file.type, //typeArray[1],
                name: file.name,
                fileSize: file.size,
            })
            if (this.ossList.length <= 0) {
                this.$message('数据异常，请刷洗后重试')
            }
            const ossFile = this.ossList[0]
            // mioIo 上传
            attachFile.path = ossFile.name
            attachFile.url = ossFile.domain + "/" + ossFile.name
            attachFile.source = ossFile.domain.split("/").pop()
            attachFile.createDate = dateFormat(new Date());
            console.log('mioIo 上传 file:', file)
            minIoImgUpdate(ossFile.link, file).then(data => {
                console.log(data, attachFile)
                add(attachFile).then(res => {
                    this.onLoad(this.page);
                })
            })

            this.ossList.splice(0, 1)
            if (this.ossList <= 0) {
                event.onSuccess()
            }
        },
        /**
         * 上传图片前检查合法性
         * @param file
         * @returns {boolean}
         */
        beforeUpload(file) {
            let typeArray = file.type.split('/')
            if (typeArray[0] !== 'image') {
                if (this.notImg) {
                    this.$message('只能上传图片')
                    this.notImg = false
                }
                return false
            }
            const isSize = file.size / (1024 * 1024) < 2
            if (!isSize) {
                this.$message('不能大于2M')
                return false
            }

            return true
        },
        /**
         * 上传错误处理
         * @param err
         * @param file
         * @param fileList
         */
        onUploadError(err, file, fileList) {
            this.$message('上传出错')
            throw err
        },
        /**
         * 上传成功处理，并提交图片数据
         * @param response
         * @param file
         * @param fileList
         * @returns {boolean}
         */
        onUploadSuccess(response, file, fileList) {
            var filesNames = []
            fileList.forEach(file => {
                filesNames.push(file.name)
            })

            console.log('上传成功处理uploadFile：', filesNames)

            this.$refs.upload.uploadFiles = []

        },
        /**
         * 选择上传文件超过限制文件个数提示
         */
        onUploadExceedTip() {
            this.message(this.$t('biz.imgbox.maxSelect') + this.uploadNumberLimit() + this.$t('biz.imgbox.unit') + this.$t('biz.imgbox.upload'))
        },
        message(msg, isInfo) {
            var type = 'error'
            if (isInfo) {
                type = 'info'
            }
            this.$message({
                message: msg,
                type: type,
                duration: 1500
            })
        }
    }
};
</script>

<style>
</style>
